package routes

import (
	"AlioServerProject/emuns"
	"AlioServerProject/utils"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

func Router() *gin.Engine {
	r := gin.Default()
	r.Use(Authentication())
	User(r)
	r.POST("/login", func(ctx *gin.Context) {
		token, _ := utils.GenerateToken(12333433, "admin")
		emuns.Success("1233")
		marshal, _ := json.Marshal(emuns.Success("1233"))
		err := utils.AddStr("name", marshal)
		fmt.Println(err)
		ctx.JSON(http.StatusOK, emuns.Success(token))
	})
	return r
}

// Authentication 认证中间件
func Authentication() gin.HandlerFunc {
	return func(r *gin.Context) {
		url := r.Request.RequestURI
		if url == "/login" || url == "/getVerificationCode" {
			r.Next()
		} else {
			token := r.Request.Header.Get("Authorization")
			if len(token) == 0 {
				r.AbortWithStatusJSON(http.StatusUnauthorized, emuns.TokenEmptyErr)
				fmt.Println(r.IsAborted())
				return
			}
			if utils.CheckToken(token) {
				r.AbortWithStatusJSON(http.StatusUnauthorized, emuns.AuthorizedErr)
				return
			}
		}
	}
}
